package com.example.zhangruoyu_zoe

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.widget.Toolbar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.zhangruoyu_zoe.activities.AddStudentActivity
import com.example.zhangruoyu_zoe.adapters.StudentAdapter
import com.example.zhangruoyu_zoe.data.Student
import com.example.zhangruoyu_zoe.utils.StudentManager

class MainActivity : AppCompatActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var addButton: Button
    private lateinit var studentManager: StudentManager
    private lateinit var studentAdapter: StudentAdapter

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 设置标题

        // 假设姓名和学号是从Intent或其他来源获取的
        val name = "张若瑜" // 这里应该是动态获取的实际姓名
        val studentId = "2022110560" // 这里应该是动态获取的实际学号

        // 组合姓名和学号作为标题
        val title = "$name$studentId"

        // 设置Activity的标题
        supportActionBar?.setTitle(title)

        recyclerView = findViewById(R.id.recyclerView)
        addButton = findViewById(R.id.addButton)

        studentManager = StudentManager(this)
        val students = studentManager.loadStudents()
        studentAdapter = StudentAdapter(students)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = studentAdapter

        addButton.setOnClickListener {
            val intent = Intent(this, AddStudentActivity::class.java)
            startActivityForResult(intent, 1)
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            val newStudent: Student? = data.getParcelableExtra<Student>("new_student")
            newStudent?.let {
                studentAdapter.addStudent(it)
                studentManager.saveStudents(studentAdapter.students) // 确保students是公开的
                Toast.makeText(this, "学生添加成功", Toast.LENGTH_SHORT).show()
            }
        }
    }
}